package com.hibase.core.rule.utils;


import com.hibase.core.rule.service.custom.CustomSerive;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * hibase规则引擎调用sql静态类
 *
 * @author hufeng
 * @date 2019/04/19
 */
@Component
public class HibaseRuleCallSqlUtils {

    private static CustomSerive customSerive;

    @Autowired
    public void setCustomSerive(CustomSerive customSerive) {
        HibaseRuleCallSqlUtils.customSerive = customSerive;
    }

    /**
     * 执行自定义的查询sql语句
     *
     * @param args 传入参数
     * @return
     */
    public static List<Map<String, Object>> executeSelectSql(String dataSourceName,Object... args) throws Exception {


        // 是否是多数据源
        Class cla = Class.forName("com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder");

        if (cla != null) {

//            Method setDataSourceLookupKey = cla.getMethod("setDataSourceLookupKey", new Class[]{String.class});
            Method setDataSourceLookupKey = cla.getMethod("push", new Class[]{String.class});
            // 设置数据源
            setDataSourceLookupKey.invoke(null, dataSourceName);
        }

        // 执行业务查询操作
        List<Map<String, Object>> result = customSerive.select(args);

        if (cla != null) {
            Method clearDataSourceLookupKey = cla.getMethod("clear");
            // 清除数据源
            clearDataSourceLookupKey.invoke(null);
        }

        return result;

    }
}
